from django.shortcuts import render, redirect
from django.contrib import messages
from login.models import NormalUser


# Create your views here.

def login(request):
    error_message = None  # 初始化 error_message 为 None
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            user = NormalUser.objects.get(username=username)
            if user.check_password(password):
                request.session['is_logged_in'] = True
                request.session['username'] = username
                return redirect('main:index')
            else:
                error_message = '用户名或密码错误'
        except NormalUser.DoesNotExist:
            error_message = '用户名不存在'
    return render(request, 'login.html', {'error_message': error_message})


def logout(request):
    request.session.pop('is_logged_in', None)
    request.session.pop('username', None)
    return redirect('login:login')


def register(request):
    error_message = None
    if request.method == 'POST':
        username = request.POST.get('username')
        password1 = request.POST.get('password1')
        password2 = request.POST.get('password2')
        phone = request.POST.get('phone')
        if password1 == password2:
            # 检查用户名是否已存在
            if NormalUser.objects.filter(username=username).exists():
                error_message = '用户名已存在，请选择其他用户名'
                return render(request, 'register.html', {'error_message': error_message})
            # 检查密码是否为空
            if not password1 or not password2:
                error_message = '密码不能为空'
                return render(request, 'register.html', {'error_message': error_message})
            # 创建新用户
            new_user = NormalUser(username=username)
            new_user.set_password(password1)
            new_user.telephone = phone
            new_user.save()
            messages.success(request, '注册成功，请登录')
            return redirect('login:login')
        else:
            error_message = '两次密码输入不一致'
            return render(request, 'register.html', {'error_message': error_message})
    return render(request, 'register.html', {'error_message': error_message})

def settings(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        avatar = request.POST.get('avatar')
        user = NormalUser.objects.get(username=username)
        user.set_password(password)
        user.avatar = avatar
        return redirect('main:index')

    return render(request, 'setting.html')
